package com.zzsy.carosshopprojects.service;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.PowerManager;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTNotificationMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.king.base.util.ToastUtils;
import com.yzy.voice.VoicePlay;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.base.ConfigureFile;
import com.zzsy.carosshopprojects.bean.BaseBean;
import com.zzsy.carosshopprojects.bean.GeTuiBean;
import com.zzsy.carosshopprojects.bean.MessageEvent;
import com.zzsy.carosshopprojects.bean.OrderDetialBean;
import com.zzsy.carosshopprojects.bean.RechargeOrderDetialBean;
import com.zzsy.carosshopprojects.network.RequestUtils;
import com.zzsy.carosshopprojects.network.Utils.MyObserver;
import com.zzsy.carosshopprojects.util.ApkInfoUtil;
import com.zzsy.carosshopprojects.util.ConverterHelper;
import com.zzsy.carosshopprojects.util.DataUtil;
import com.zzsy.carosshopprojects.util.FormatTimeUtil;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.util.sunmiprint.PrintHelper;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;

public class CareoeIntentService extends GTIntentService {
    private Gson gson;
    private GsonBuilder builder;
    /**
     * 为了观察透传数据变化.
     */
    private static int cnt;

    private Context mContext;

    private String qrSwitch;

    private String gzhSwitch;

    private String rechargeBalanceDou = "";
    private double redPackedAmountDou;
    private double redPackedSumDou;
    private String storeName;
    private double goodsCouponAmountDou;
    private String certificationTypeName;
    private String carNumber;
    private String musicSwitch;

    @Override
    public void onReceiveServicePid(Context context, int pid) {
        Log.d(TAG, "onReceiveServicePid -> " + pid);
    }

    @Override
    public void onReceiveClientId(Context context, String clientid) {
        Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        /**
         * P2屏幕唤醒
         */
        String versionData = ApkInfoUtil.getVersionData();
        if (!StringUtils.isEmpty(versionData)) {
            if ("P1_4G".equals(versionData)) {

            } else {
                ScreenWake();
            }
        } else {
            ScreenWake();
        }
        this.mContext = context;
        qrSwitch = DataUtil.getInstance().getQrSwitch();
        musicSwitch = DataUtil.getInstance().getMusicSwitch();
        // 透传消息的处理方式，详看SDK demo
        String appid = msg.getAppid();
        String taskid = msg.getTaskId();
        String messageid = msg.getMessageId();
        byte[] payload = msg.getPayload();
        String pkg = msg.getPkgName();
        String cid = msg.getClientId();
        //这两句代码必须的，为的是初始化出来gson这个对象，才能拿来用
        builder = new GsonBuilder();
        gson = builder.create();
        // 第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
        boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
        Log.d(TAG, "call sendFeedbackMessage = " + (result ? "success" : "failed"));
        Log.d(TAG, "onReceiveMessageData -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nmessageid = " + messageid + "\npkg = " + pkg
                + "\ncid = " + cid);
        if (payload == null) {
            Log.e(TAG, "receiver payload = null");
        } else {
            String data = new String(payload);
            Log.d(TAG, "receiver payload = " + data);
            // 测试消息为了观察数据变化
            if (data.equals(getResources().getString(R.string.push_transmission_data))) {
                data = data + "-" + cnt;
                cnt++;
            }
            Log.d(TAG, "----------------------" + data);
            GeTuiBean geTuiBean = gson.fromJson(data, GeTuiBean.class);
            String type = geTuiBean.getType();
            if (!StringUtils.isEmpty(type)) {
                /**
                 * 1：消费
                 * 2. 充值
                 * */
                if ("1".equals(type)) {
                    setOrderData(geTuiBean.getGetuiOrderDTO());
                } else if ("2".equals(type)) {
                    setReghterData(geTuiBean.getGetuiRorderDTO());
                }
            }
        }
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean b) {

    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage gtCmdMessage) {

    }

    @Override
    public void onNotificationMessageArrived(Context context, GTNotificationMessage gtNotificationMessage) {
        Log.e(TAG, "收到了吗");
    }

    @Override
    public void onNotificationMessageClicked(Context context, GTNotificationMessage gtNotificationMessage) {
        Log.e(TAG, "到这收到了吗/");
    }

    /**
     * 消费
     */
    private void setOrderData(GeTuiBean.GetuiOrderDTO getuiOrderDTO) {
        Log.d("数据接收：---------------", getuiOrderDTO.getOrderAmount() + getuiOrderDTO.getPayAmount());
        String payAmount1 = getuiOrderDTO.getOrderAmount();
        if (!StringUtils.isEmpty(payAmount1)) {
            if (!StringUtils.isEmpty(musicSwitch)) {
                if ("1".equals(musicSwitch)) {
                    //VoicePlay.with(mContext).play(payAmount1, false);
                    VoicePlay.with(getApplication()).play(payAmount1, false);
                }
            }
        }
        /**支付成功 通知界面刷新**/
        EventBus.getDefault().post(new MessageEvent(MessageEvent.PAYSUCESS));

        if (!StringUtils.isEmpty(getuiOrderDTO.getType())) {
            if (getuiOrderDTO.getType().equals("2") || getuiOrderDTO.getType().equals("4")) {
                /**查询小票是否可以打印**/
                IsPrintTicket(getuiOrderDTO.getOrderNumber(), getuiOrderDTO);
            } else {
                ToastUtils.showToast(mContext.getApplicationContext(), getApplicationContext().getResources().getString(R.string.msgError));
            }

        }

    }

    /**
     * 充值、
     */
    private void setReghterData(GeTuiBean.GetuiRorderDTO getuiRorderDTO) {
        String rechargeNumber = getuiRorderDTO.getRechargeNumber();
        String amount = getuiRorderDTO.getAmount();
        if (!StringUtils.isEmpty(amount)) {
            if (!StringUtils.isEmpty(musicSwitch)) {
                if ("1".equals(musicSwitch)) {
                    VoicePlay.with(mContext).play(amount, false);
                }
            }
        }
        /**充值成功 通知界面刷新**/
        EventBus.getDefault().post(new MessageEvent(MessageEvent.RECHARGESUCESS));

        IsPrintRechargeTicket(rechargeNumber, getuiRorderDTO);
    }

    /**
     * 查询是否可以打印小票
     *
     * @param
     * @param orderNumber 订单编号
     */
    public void IsPrintTicket(String orderNumber, GeTuiBean.GetuiOrderDTO getuiOrderDTO) {
        RequestUtils.UpdatePrintStatus(mContext, orderNumber, new MyObserver<BaseBean>(mContext, false) {
            @Override
            public void onSuccess(BaseBean result) {

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                if (code == ConfigureFile.code) {
                    if ("2".equals(getuiOrderDTO.getType())) {
                        getOrderDetail(2, orderNumber, getuiOrderDTO);
//                        if (StringUtils.isEmpty(getuiOrderDTO.getPayRule()))//一键加油
//                        {
//                            getOrderDetail(2, orderNumber, getuiOrderDTO);
//                        } else//快速加油加油
//                        {
//                            getOrderDetail(3, orderNumber, getuiOrderDTO);
//                        }

                    } else if ("4".equals(getuiOrderDTO.getType())) {//操作员收费成功后的小票
                        getOrderDetail(4, orderNumber, getuiOrderDTO);
                    }

                } else {
                    ToastUtils.showToast(mContext.getApplicationContext(), errorMsg);
                }
            }
        });
    }

    /**
     * 查询是否可以打印充值小票
     *
     * @param orderNumber
     * @param getuiRorderDTO
     */
    public void IsPrintRechargeTicket(String orderNumber, GeTuiBean.GetuiRorderDTO getuiRorderDTO) {
        RequestUtils.UpdatePrintStatus(mContext, orderNumber, new MyObserver<BaseBean>(mContext, false) {
            @Override
            public void onSuccess(BaseBean result) {

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                if (code == ConfigureFile.code) {
                    String rechargeNumber = getuiRorderDTO.getRechargeNumber();
                    String amount = getuiRorderDTO.getAmount();
                    String storeName = getuiRorderDTO.getStoreName();
                    String payTypeReghter = getuiRorderDTO.getPayType();
                    String orderCreateTime = getuiRorderDTO.getOrderCreateTime();
                    String memberCouponAmounts = getuiRorderDTO.getMemberCouponAmounts();
                    String memberBlanceAmounts = getuiRorderDTO.getMemberBlanceAmounts();
                    if (StringUtils.isEmpty(memberBlanceAmounts)) {
                        memberBlanceAmounts = "0";
                    }
                    if (StringUtils.isEmpty(memberCouponAmounts)) {
                        memberCouponAmounts = "0";
                    }
                    String memberBlanceAmountsDou = ConverterHelper.toBigDecimal(memberBlanceAmounts).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                    String memberCouponAmountsDou = ConverterHelper.toBigDecimal(memberCouponAmounts).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                    getOrderDetialData(rechargeNumber, amount, storeName, orderCreateTime, payTypeReghter, memberBlanceAmountsDou, memberCouponAmountsDou);
                } else {
                    ToastUtils.showToast(mContext.getApplicationContext(), errorMsg);
                }
            }
        });
    }


    /**
     * 调取充值订单详情
     *
     * @param rechargeNumber
     * @param amount
     * @param storeName
     * @param orderCreateTime
     * @param payTypeReghter
     * @param memberBlanceAmountsDou
     * @param memberCouponAmountsDou
     */

    private void getOrderDetialData(String rechargeNumber, String amount, String storeName, String orderCreateTime, String payTypeReghter, String memberBlanceAmountsDou, String memberCouponAmountsDou) {
        RequestUtils.GetROrder(mContext, rechargeNumber, new MyObserver<RechargeOrderDetialBean>(mContext, false) {
            @Override
            public void onSuccess(RechargeOrderDetialBean bean) {
                if (bean != null) {
                    String printStatus = bean.getPrintStatus();
                    String memberPhone = bean.getPhone();
                    String rechargeBalance = bean.getRechargeBalance();
                    if (!StringUtils.isEmpty(rechargeBalance)) {
                        rechargeBalanceDou = ConverterHelper.toBigDecimal(rechargeBalance).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                    } else {
                        rechargeBalanceDou = "0";
                    }
                    String oilType = "";
                    if (bean.getProductId() != null) {
                        if (bean.getProductId().equals("1")) {
                            oilType = "柴油";
                        } else if (bean.getProductId().equals("2")) {
                            oilType = "汽油";
                        } else if (bean.getProductId().equals("25")) {
                            oilType = "LNG";
                        } else if (bean.getProductId().equals("26")) {
                            oilType = "CNG";
                        }
                    }
                    String redPackedAmount = bean.getRedPackedAmount();
                    String redPackedSum = bean.getRedPackedSum();
                    if (StringUtils.isEmpty(redPackedAmount)) {
                        redPackedAmount = "0";
                    }
                    redPackedAmountDou = ConverterHelper.toBigDecimal(redPackedAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    redPackedSumDou = ConverterHelper.toBigDecimal(redPackedSum).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    String goodsCouponAmount = bean.getGoodsCouponAmount();
                    if (StringUtils.isEmpty(goodsCouponAmount)) {
                        goodsCouponAmount = "0";
                    }
                    goodsCouponAmountDou = ConverterHelper.toBigDecimal(goodsCouponAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                    if (StringUtils.isEmpty(memberPhone)) {
                        memberPhone = "";
                    }
                    String amounts = ConverterHelper.toBigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                    String payTypeStr = "";
                    String time = "";
                    if (!StringUtils.isEmpty(orderCreateTime)) {
                        time = FormatTimeUtil.formatTimeStamp2DateStr(String.valueOf(Long.parseLong(orderCreateTime) / 1000), "yyyy-MM-dd HH:mm:ss");
                    }
                    if ("1".equals(payTypeReghter)) {
                        payTypeStr = "支付宝支付";
                    } else if ("2".equals(payTypeReghter)) {
                        payTypeStr = "微信支付";
                    } else if ("3".equals(payTypeReghter)) {
                        payTypeStr = "银联支付";
                    } else if ("4".equals(payTypeReghter)) {
                        payTypeStr = "余额支付";
                    } else if ("5".equals(payTypeReghter)) {
                        payTypeStr = "现金支付";
                    }
                    if (!StringUtils.isEmpty(printStatus)) {
//                        if ("0".equals(printStatus)) {
//                            PrintHelper.getInstance().PrintRechargeOrder(rechargeNumber, time, amounts, storeName, payTypeStr, Double.valueOf(rechargeBalanceDou), memberPhone,
//                                    redPackedAmountDou, goodsCouponAmountDou, redPackedSumDou, oilType, bean.getReductionCouponAmount(),false);
//                        }
                        PrintHelper.getInstance().PrintRechargeOrder(rechargeNumber, time, amounts, storeName, payTypeStr, Double.valueOf(rechargeBalanceDou), memberPhone,
                                redPackedAmountDou, goodsCouponAmountDou, redPackedSumDou, oilType, bean.getReductionCouponAmount(), false);
                    }
                }

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                ToastUtils.showToast(mContext.getApplicationContext(), errorMsg);
            }
        });


    }


    /**
     * 获取订单详情接口
     *
     * @param
     * @param orderNumber
     */
    public void getOrderDetail(int kind, String orderNumber, GeTuiBean.GetuiOrderDTO getuiOrderDTO) {
        RequestUtils.OrderDetail(mContext, orderNumber, new MyObserver<OrderDetialBean>(mContext, false) {
            @Override
            public void onSuccess(OrderDetialBean result) {
                if (kind == 2) {
                    String orderAmount = getuiOrderDTO.getOrderAmount();
                    String payAmount = getuiOrderDTO.getPayAmount();
                    String oilNum = getuiOrderDTO.getOilNum();
                    String time = getuiOrderDTO.getTime();
                    String orderId = getuiOrderDTO.getOrderNumber();
                    String phone = getuiOrderDTO.getPhone();
                    String pageSkip = getuiOrderDTO.getPageSkip();
                    String activityReduction = getuiOrderDTO.getActivityReduction();
                    if (StringUtils.isEmpty(activityReduction)) {
                        activityReduction = "";
                    }
                    if (StringUtils.isEmpty(orderAmount)) {
                        orderAmount = "";
                    }
                    if (StringUtils.isEmpty(payAmount)) {
                        payAmount = "";
                    }
                    String oilPrice = result.getOilPrice();
                    double oilsPrices;
                    if (!StringUtils.isEmpty(oilPrice)) {
                        BigDecimal bigDecimalAmount = ConverterHelper.toBigDecimal(oilPrice).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        oilsPrices = bigDecimalAmount.doubleValue();

                    } else {

                        oilsPrices = 0;
                    }
                    String printStatus = result.getPrintStatus();
                    String payType = result.getPayType();
                    String payTypeStr = "";
                    if (!StringUtils.isEmpty(payType)) {
                        if ("1".equals(payType)) {
                            payTypeStr = "支付宝支付";
                        } else if ("2".equals(payType)) {
                            payTypeStr = "微信支付";
                        } else if ("3".equals(payType)) {
                            payTypeStr = "银联支付";
                        } else if ("4".equals(payType)) {
                            payTypeStr = "余额支付";
                        }
                    }
                    String title = "";
                    if (StringUtils.isEmpty(getuiOrderDTO.getPayRule())) {
                        title = "消费凭证(一键加油)";
                    } else {
                        if (getuiOrderDTO.getPayRule().equals("6"))
                            title = "消费凭证(快捷加油)";
                        else
                            title = "消费凭证(一键加油)";
                    }
                    PrintHelper.getInstance().getPrintOrder(title, orderAmount, payAmount, result.getStoreName(), Double.valueOf(activityReduction),
                            oilNum, time, orderId, phone, payTypeStr,
                            Double.valueOf(result.getRise()), oilsPrices, result.getOilPriceSwitch(), result.getCertificationTypeName(), result.getCarNumber(), false);

                } else if (kind == 4) {
                    PrintHelper.getInstance().PrintOperatorChargeTicket(result, false);
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                ToastUtils.showToast(mContext.getApplicationContext(), errorMsg);
            }
        });


    }

    /**
     * 屏幕唤醒
     *
     * @param
     */
    public void ScreenWake() {
        try {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
            wl.acquire();
            wl.release();
        } catch (Exception e) {
            Log.d("dddd", "唤醒屏幕错误");
        }

    }

}
